# #!/usr/bin/env python
# # -*- coding: utf-8 -*-
# # @Time    : 2020/7/7 16:38
# # @Author  : CoderCharm
# # @File    : curd_user.py
# # @Software: PyCharm
# # @Desc    :
# """
#
# """
#
import re
from typing import Optional

from sqlalchemy.orm import Session

# from core.security import get_password_hash, verify_password
from api.common.curd_base import CRUDBase
from api.models.auth import User

from core.security import verify_password
from ..schemas import user_schema
import random
import captcha
from api.utils.my_redis import MyRedis
from api.utils.my_rong import Sms
from api.utils.my_jwt import MyJwt
from api.utils.captcha.captcha.captcha import captcha
from flask import Blueprint,jsonify, make_response


class CRUDUser(CRUDBase[User, user_schema.UserCreate, user_schema.UserUpdate]):
    # def get_msgcode(self,obj_in:user_schema.MsgCode):
    #     if obj_in.imgcode ==

    def get_imgcode(self,uuid:str):
        name, text, image = captcha.generate_captcha()
        print(image)
        res = make_response(image)
        res.headers['Content-Type'] = 'image/jpg'
        # 存入redis
        MyRedis().set_str(uuid, text)
        print(res)
        return res

    def authenticate(self, db: Session, *, account: str, password: str) -> Optional[User]:
        user_info = db.query(User).filter(User.account == account).first()
        if not user_info:
            return {
                "code":400,
                "msg":"用户不存在"
            }
        if user_info.password_hash != password:
            return {
                "code":400,
                "msg":"密码错误"
            }
        data = {
            "id":user_info.id,
            "rid":user_info.role_id,
            "mobile":user_info.account,
        }
        token = MyJwt().jwt_encode(data=data)
        return {
            "token":token
        }

    # 验证手机号和密码是否为空
    def username_verify(self, *, account: int, password: str,msg_code:str) -> str:
        # 手机号和密码是否为空
        if not all([account, password]):
            return '1001'
        res = re.match('^1[3-9]\d{9}$', str(account))
        if not res:
            return '1002'
        key = 'msg_code'+str(account)
        code = MyRedis().get_str(key)
        if code != str(msg_code):
            return "1003"
        return '201'

    def send_message(self,db:Session,*,mobile:int,imgcode:str,uuid:str):
        res_imgcode = MyRedis().get(uuid)
        if res_imgcode != imgcode:
            return {
                "code":401,
                "msg":"图形验证码错误无法发起短信"
            }
        code = random.randint(10000,99999)
        key = "msg_code"+str(mobile)
        MyRedis().set_str(key,code)
        msg = Sms().send(mobile=mobile,code=code)
        if msg:
            return {
                "code":200,
                "msg":'发送成功'
            }
        else:
            return {
                "code":400,
                "msg":"发送失败"
            }


    # @staticmethod
    # def get_by_email(db: Session, *, email: str) -> Optional[User]:
    #     """
    #     通过email获取用户
    #     参数里面的* 表示 后面调用的时候 要用指定参数的方法调用
    #     正确调用方式
    #         curd_user.get_by_email(db, email="xxx")
    #     错误调用方式
    #         curd_user.get_by_email(db, "xxx")
    #     :param db:
    #     :param email:
    #     :return:
    #     """
    #     return db.query(AdminUser).filter(AdminUser.email == email).first()
    #
    # def create(self, db: Session, *, obj_in: user_schema.UserCreate) -> AdminUser:
    #     db_obj = AdminUser(
    #         nickname=obj_in.nickname,
    #         email=obj_in.email,
    #         hashed_password=get_password_hash(obj_in.password),
    #         avatar=obj_in.avatar,
    #         role_id=obj_in.role_id,
    #         is_active=obj_in.is_active
    #     )
    #     db.add(db_obj)
    #     db.commit()
    #     db.refresh(db_obj)
    #     return db_obj

    # def authenticate(self, db: Session, *, email: str, password: str) -> Optional[AdminUser]:
    #     user = self.get_by_email(db, email=email)
    #     if not user:
    #         return None
    #     if not verify_password(password, user.hashed_password):
    #         return None
    #     return user

    # @staticmethod
    # def is_active(user: AdminUser) -> bool:
    #     return user.is_active == 1

    # def login(self,db:Session,*,obj_in:user_schema.login):
    #     res =  db.query(User).filter(User.is_delete == 0,User.account == obj_in.mobile)
    #     if res:

curd_user = CRUDUser(User)
